package com.rfs.collections;

import cn.hutool.core.util.ArrayUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class ArrayTest {
    public static void main(String[] args) throws Exception {
        String plaintext = "Hello, World!";
        String key = "12345678123456781234567812345678";
        String vi = "0000000000000000";

        // 加密
        byte[] encryptedBytes = encrypt(plaintext, key, vi);
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("加密后的文本：" + encryptedText);
        // 解密
        byte[] decryptedBytes = decrypt(encryptedBytes, key, vi);
        String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
        System.out.println("解密后的文本：" + decryptedText);
    }

    public static byte[] encrypt(String plaintext, String key, String vi) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(vi.getBytes(StandardCharsets.UTF_8)));
        return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
    }

    public static byte[] decrypt(byte[] ciphertext, String key, String vi) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(vi.getBytes(StandardCharsets.UTF_8)));
        return cipher.doFinal(ciphertext);
    }
}
